<?php


namespace app\index\controller;


use think\facade\Log;

class Wechat extends BaseWechat
{
    /**
     * 使用code换取access_token
     * @param string 用于换取access_token的code，微信提供
     * @return array access_token和用户openid数组
     */
    public function accessToken($code)
    {
        $appid = $this->Appid;
        $appsecret = $this->AppSecret;
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $appsecret . '&code=' . $code . '&grant_type=authorization_code';
        $user = json_decode(file_get_contents($url));
        if (isset($user->errcode)) {
            echo 'error:' . $user->errcode.'<hr>msg  :' . $user->errmsg;exit;
        }
        $data = json_decode(json_encode($user),true);//返回的json数组转换成array数组
        return $data;
    }

    /**
     * 使用access_token获取用户信息
     * @param string access_token
     * @param string 用户的openid
     * @return array 用户信息数组
     */
    public function getWechatInfo($access_token,$openid)
    {
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
        $user = json_decode(file_get_contents($url));
        if (isset($user->errcode)) {
            echo 'error:' . $user->errcode.'<hr>msg  :' . $user->errmsg;exit;
        }
        $data = json_decode(json_encode($user),true);//返回的json数组转换成array数
        return $data;
    }

    /**
     * 用户授权并获取code
     * @param string $callback 微信服务器回调链接url
     */
    public function getCode($callback,$sign='')
    {
        $appid = $this->Appid;
        $scope = 'snsapi_userinfo';
        $state = $sign.'_and_'.md5(uniqid((string)mt_rand(), TRUE));//唯一ID标识符绝对不会重复
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . urlencode($callback) .  '&response_type=code&scope=' . $scope . '&state=' . $state . '#wechat_redirect';
        Log::write('code不存在，我是拼接好微信的回调url:' .$url, 'error');
        echo "<script>location.href='".$url."'</script>";
    }
}